package org.megha.blog.example.concurrency;

/**
 * Runs IncrementorThreads that increment a {@link Counter} in parallel.
 * 
 * @author megha birmiwal
 */
public class CounterRunner {

	private final IncrementorThread[] threads;
	private final Counter counter;

	public CounterRunner(Counter counter, IncrementorThread... threads) {
		this.threads = threads;
		this.counter = counter;
	}
	
	public void execute() throws InterruptedException {
		for (Thread thread : threads) {
			thread.start();
		}
		
		for (Thread thread : threads) {
			thread.join();
		}
		
		System.out.println("Counter is: " + counter.getCount());
	}

	public static void main(String args[]) throws InterruptedException {
		final int TIMES = 50000;
		Counter counter = new Counter();
		IncrementorThread t1 = new IncrementorThread(TIMES, counter);
		IncrementorThread t2 = new IncrementorThread(TIMES, counter);
		IncrementorThread t3 = new IncrementorThread(TIMES, counter);
		new CounterRunner(counter, t1, t2, t3).execute();
	}
}
